import os, re

#@cache(request.env.path_info,600,cache.ram)

class Book:
  @classmethod
  def set_filename(self, filename=""):
      if filename: self.filename = filename
      return self.filename or False

  @classmethod
  def set_bookname(self):
      self.bookname = re.findall("^[a-z]+", self.filename)[0]
      return self.bookname or False

def dec_arguments(fn):
  def wrap(*args):
      try:
        Book.set_filename(request.args[0])
        Book.set_bookname()
      except IndexError:
        pass
      else:
        try:
          db.book.insert(action=request.function,
              remote_addr=request.env.remote_addr, filename=Book.filename, name=Book.bookname)
        except AttributeError:
          pass
      return fn()
  return wrap

@dec_arguments
def index():
    try:
      bookname=request.args[-1]
    except IndexError: 
      bookname=BOOKS[0]
    return dict(bookname=bookname)

@dec_arguments
def preview():
    filename=Book.filename
    bookname=Book.bookname
    filename_download=filename.replace("_thumb", "")
    visits=db((db.book.action=='preview')&(db.book.filename==filename)&(db.book.name==bookname)).count()
    filename=filename.replace("thumb", "preview")
    downloads=db((db.book.action=='download_preview')&(db.book.filename==filename)&(db.book.name==bookname)).count()
    downloads+=db((db.book.action=='download_file')&(db.book.filename==filename)&(db.book.name==bookname)).count()
    return dict(filename=filename, visits=visits, downloads=downloads, filename_download=filename_download, bookname=bookname)

@dec_arguments
def download_preview():
    filename=Book.filename
    bookname=Book.bookname
    filename = filename.replace("_preview", "")
    #__update(filename, bookname)
    return dict(filename=filename)

@dec_arguments
def download_file():
    import gluon.contenttype
    filename=Book.filename
    bookname=Book.bookname
    filename = filename.replace("_preview", "")
    #__update(filename, bookname)
    response.headers['Content-Type']=\
         gluon.contenttype.contenttype(filename)
    response.headers['Content-Disposition: attachment; filename="%s"' % filename] = True
    return open('applications/%s/static/book/download/%s' %
         (request.application,filename),'rb').read()

    
